<template>
  <div>
    <h1>账单汇总</h1>
    <el-row class="count_row mb20">
      <el-col class="count_cell" :span="8">
        <div class="title"><span class="name">可提现(元)</span></div>
        <big>{{accountData.withdrawPrice}}</big>
        <el-button type="primary" @click="showWithdrawal()" :disabled="accountData.withdrawPrice==0">提现</el-button>
      </el-col>
      <el-col class="count_cell" :span="8">
        <div class="title"><span class="name">待审核(元)</span></div>
        <big>{{accountData.outPrice}}</big>
      </el-col>
      <el-col class="count_cell" :span="8">
        <div class="title"><span class="name">未出账(元)</span></div>
        <big>{{accountData.noOutPrice}}</big>
      </el-col>
    </el-row>
    <h1>账单列表</h1>
    <en-table-layout
      pagination
      :tableData="tableData"
      :loading="loading">
      <template slot="table-columns">
        <!--结算编号-->
        <el-table-column prop="bill_sn" label="结算编号" min-width="160" />
        <!--起止时间-->
        <el-table-column label="起止时间" min-width="280">
          <template slot-scope="scope">
            {{ scope.row.start_time | unixToDate }} - {{ scope.row.end_time | unixToDate }}
          </template>
        </el-table-column>
        <!--本期应收-->
        <el-table-column label="本期应收" width="120">
          <template slot-scope="scope">{{ scope.row.bill_price | unitPrice('￥') }}</template>
        </el-table-column>
        <!--结算状态-->
        <el-table-column prop="status_text" label="结算状态" width="120"/>
        <!--付款时间-->
        <el-table-column label="付款时间" width="180">
          <template slot-scope="scope">
            {{ scope.row.pay_time | unixToDate }}
          </template>
        </el-table-column>
        <!--操作-->
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="handleQueryDetail(scope.$index, scope.row)">查看详情
            </el-button>
          </template>
        </el-table-column>
      </template>
      <el-pagination
        slot="pagination"
        v-if="pageData"
        @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange"
        :current-page="pageData.page_no"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.data_total">
      </el-pagination>
    </en-table-layout>

    <!--提现-->
    <el-dialog
      title="提现申请"
      width="430px"
      class="dialog-withdrawal"
      :visible.sync="dialogWithdrawal">
      <el-form :model="formWithdrawal" :rules="formWithdrawalRules" ref="formWithdrawal" label-width="100px">
        <el-form-item label="提现方式:" :rules="{ required: true, message: '请选择提现方式' ,trigger: 'blur' }">
          <el-radio-group v-model="withdrawal_type" @change="changeType">
            <el-radio label=2>支付宝</el-radio>
            <el-radio label=1>银行卡</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 银行卡star -->
        <el-form-item label="账户类型:" prop="bank_card_type" v-if="showBank">
          <el-select v-model="formWithdrawal.bank_card_type" placeholder="请选择账户类型">
            <el-option label="个人账户" value='0'></el-option>
            <el-option label="企业账户" value='1'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开户银行:" prop="bank_name" v-if="showBank">
          <dg-select v-model="formWithdrawal.bank_name" dictType="bank_name" placeholder="请选择开户银行" :defaultValue="formWithdrawal.bank_name" clearable></dg-select>
        </el-form-item>
        <el-form-item label="银行账号:" prop="card_no" v-if="showBank">
          <el-input v-model="formWithdrawal.card_no"></el-input>
        </el-form-item>
        <el-form-item label="账户姓名:" prop="open_account_name" v-if="showBank">
          <el-input v-model="formWithdrawal.open_account_name"></el-input>
        </el-form-item>
        <el-form-item label="支行名称:" prop="sub_bank_name" v-if="accountType && showBank">
          <el-input v-model="formWithdrawal.sub_bank_name"></el-input>
        </el-form-item>
        <el-form-item label="开户城市:" v-if="accountType && showBank" prop="bank_province">
          <div class="showCitySelect">
            <el-form-item>
              <el-select v-model="formWithdrawal.bank_province" placeholder="请选择省份" @change="getCityDatas(formWithdrawal.bank_province, 'city', 'clearCity')">
                <el-option
                  v-for="item in bank_provinceDatas"
                  :key="item.id"
                  :label="item.local_name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="bank_city">
              <el-select v-model="formWithdrawal.bank_city" ref='bankCity' placeholder="请选择城市" @change="getCityDatas(formWithdrawal.bank_city)">
                <el-option
                  v-for="item in bank_cityDatas"
                  :key="item.id"
                  :label="item.local_name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form-item>
        <!-- 银行卡end -->
        <!-- 支付宝star -->
        <el-form-item label="账户类型:" prop="ofPublic" v-if="!showBank">
          <el-select v-model="formWithdrawal.ofPublic" placeholder="请选择账户类型">
            <el-option label="个人账户" value='0'></el-option>
            <el-option label="企业账户" value='1'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账户姓名:" prop="accountName" v-if="!showBank">
          <el-input v-model="formWithdrawal.accountName"></el-input>
        </el-form-item>
        <el-form-item label="收款账号:" prop="accountNo" v-if="!showBank">
          <el-input v-model="formWithdrawal.accountNo"></el-input>
        </el-form-item>
        <!-- 支付宝end -->
        <div class="borderHr"></div>
        <el-form-item label="提现金额:" prop="apply_money" auto-complete="new-accounts">
          <el-input v-model.number="formWithdrawal.apply_money"></el-input>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="formWithdrawal.password" type="password" auto-complete="new-accounts" clearable placeholder="请输入密码" maxlength="20"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCansle">取 消</el-button>
        <el-button type="primary" @click="submitWithdrawal()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as API_settlement from '@/api/settlement'
  import { CategoryPicker } from '@/components'
  import dg_select from '@/components/dg-select'
  import { getDictData } from '@/common/filter-show'
  import $axios from 'axios'

  let timeFlag = 1
  let timeI = 60
  export default {
    name: 'settlementManage',
    components: {
      [CategoryPicker.name]: CategoryPicker,
      'dg-select': dg_select
    },
    data() {
      return {
        /** 列表loading状态 */
        loading: false,

        /** 列表参数 */
        params: {
          page_no: 1,
          page_size: 10
        },

        /** 账单汇总 */
        accountData: {
          withdrawPrice: 0.00,
          outPrice: 0.00,
          noOutPrice: 0.00
        },

        /** 列表数据 */
        tableData: null,

        /** 列表分页数据 */
        pageData: null,

        /** 提现弹层 */
        dialogWithdrawal: false,
        formWithdrawal: {
          bank_card_type: '0',
          bank_name: '',
          card_no: '',
          open_account_name: '',
          sub_bank_name: '',
          bank_account_name: '',
          bank_province: null,
          bank_city: null,
          bankId: '',
          alipayId: '',
          ofPublic: '0',
          accountName: '',
          accountNo: '',
          apply_money: null,
          password: ''
        },
        bank_selectDatas: [],
        bank_provinceDatas: [],
        bank_cityDatas: [],
        withdrawal_type: '2',
        formWithdrawalRules: {
          bank_card_type: [
            {
              required: true,
              message: '请选择账户类型'
            }
          ],
          bank_name: [
            {
              required: true,
              message: '请选择开户银行'
            }
          ],
          card_no: [
            {
              required: true,
              message: '请输入账银行账号'
            }
          ],
          open_account_name: [
            {
              required: true,
              message: '请输入账户姓名'
            }
          ],
          sub_bank_name: [
            {
              required: true,
              message: '请选择支行名称'
            }
          ],
          bank_province: [
            {
              required: true,
              message: '请选择开户省'
            }
          ],
          bank_city: [
            {
              required: true,
              message: '请选择开户城市'
            }
          ],

          ofPublic: [
            {
              required: true,
              message: '请选择账户类型'
            }
          ],
          accountName: [
            {
              required: true,
              message: '请输入账户名称'
            }
          ],
          accountNo: [
            {
              required: true,
              message: '请输入收款账号'
            }
          ],

          apply_money: [
            {
              required: true,
              message: '请输入提现金额'
            }
          ],
          password: [
            {
              required: true,
              message: '请输入提现密码'
            }
          ]
        },
        codeDiasbled: false,
        appendBtnText: '获取验证码'
      }
    },
    computed: {
      showBank () {
        return this.withdrawal_type === '1' ? 1 : 0;
      },
      accountType () {
        return this.formWithdrawal.bank_card_type === '1' ? 1 : 0;
      }
    },
    mounted() {
      // 获取格式化字典数据
      getDictData('bank_name');
      this.GET_CountAccount();
      this.GET_SetTelMentList();
    },
    methods: {
      /** 获取账户汇总 */
      GET_CountAccount() {
        this.loading = true
        API_settlement.getCountAccount().then(response => {
          this.loading = false
          this.accountData = { ...response }
        })
      },
      /** 分页大小发生改变 */
      handlePageSizeChange(size) {
        this.params.page_size = size
        this.GET_SetTelMentList()
      },
      /** 分页页数发生改变 */
      handlePageCurrentChange(page) {
        this.params.page_no = page
        this.GET_SetTelMentList()
      },
      /** 查看详情 传递结算单号*/
      handleQueryDetail(index, row) {
        this.$router.push({ path: `/order/settlement-detail/${row.bill_id}` })
      },
      /** 获取结算单列表 */
      GET_SetTelMentList() {
        this.loading = true
        API_settlement.getSettleMentList(this.params).then(response => {
          this.loading = false
          this.tableData = response.data
          this.pageData = {
            page_no: response.page_no,
            page_size: response.page_size,
            data_total: response.data_total
          }
        })
      },

      handleCansle (){
        this.dialogWithdrawal = false;
        this.$refs['formWithdrawal'].resetFields();
      },
      /** 显示提现弹框 */
      showWithdrawal() {
        this.loading = true
        API_settlement.getWithdrawInfo().then(response => {
          this.loading = false
          this.dialogWithdrawal = true;
          this.getCityDatas(0, 'province');
          let webBankData = response.webBankCard
          let alipayData = response.alipayWithdrawAccount

          if (webBankData) {
            this.formWithdrawal.bank_name = webBankData.bank_name;
            this.formWithdrawal.card_no = webBankData.card_no;
            this.formWithdrawal.bankId = webBankData.id;
            this.formWithdrawal.open_account_name = webBankData.open_account_name;
            this.formWithdrawal.sub_bank_name = webBankData.sub_bank_name;
            this.formWithdrawal.bank_province = webBankData.bank_province_id;
            this.formWithdrawal.bank_city = webBankData.bank_city_id;
            this.formWithdrawal.bank_card_type = webBankData.bank_card_type.toString();
          }
          if (this.formWithdrawal.bank_province) {
            this.getCityDatas (this.formWithdrawal.bank_province, 'city');
          }
          if (alipayData) {
            this.formWithdrawal.accountName = alipayData.accountName;
            this.formWithdrawal.accountNo = alipayData.accountNo;
            this.formWithdrawal.ofPublic = alipayData.ofPublic.toString();
            this.formWithdrawal.alipayId = alipayData.id;
          }
        })
      },
      /** 提现申请提交 */
      submitWithdrawal() {
        this.$refs['formWithdrawal'].validate((valid) => {
          if (valid) {
            this.checkPassword ();
            this.loading = true;
          }
        })
      },
      /* 验证密码 */
      checkPassword () {
        if (this.formWithdrawal.apply_money > this.accountData.withdrawPrice) {
          this.$message.error('提现金额不能大于账户余额');
          return;
        }
        API_settlement.checkPassword(this.formWithdrawal.password).then(response => {
          if ( this.showBank) {
            if ( this.formWithdrawal.bankId ) {
              this.updateBankCard();
            } else {
              this.bindBankCard();
            }
          } else {
            if ( this.formWithdrawal.alipayId ) {
              this.updateWithdrawAccount();
            } else {
              this.submitWithdrawAccount();
            }
          }
        }).catch( (err) => {
          this.$message.error(err);
        })
      },
      /* 提交支付宝账号 */
      submitWithdrawAccount () {
        let _params = {
          account_name: this.formWithdrawal.accountName,
          account_no: this.formWithdrawal.accountNo,
          of_public: this.formWithdrawal.ofPublic,
          type: 1
        }
        API_settlement.submitWithdrawAccount(_params).then(response => {
          // this.$message.success(response.message);
          this.applyWithdraw();
        }).catch( (err) => {
          this.$message.error(err);
        })
      },
      /* 修改支付宝账号 */
      updateWithdrawAccount () {
        let _params = {
          account_name: this.formWithdrawal.accountName,
          account_no: this.formWithdrawal.accountNo,
          id: this.formWithdrawal.alipayId,
          of_public: this.formWithdrawal.ofPublic,
          type: 1
        }
        API_settlement.updateWithdrawAccount(_params).then(response => {
          // this.$message.success(response.message);
          this.applyWithdraw();
        }).catch( (err) => {
          this.$message.error(err);
        })
      },
      /* 提交银行卡账号 */
      bindBankCard () {
        let _params = {
          bank_card_type: this.formWithdrawal.bank_card_type,
          bank_name: this.formWithdrawal.bank_name,
          card_no: this.formWithdrawal.card_no,
          open_account_name: this.formWithdrawal.open_account_name,
          sub_bank_name: this.formWithdrawal.sub_bank_name,
          bank_province_id: this.formWithdrawal.bank_province,
          bank_city_id: this.formWithdrawal.bank_city
        }
        API_settlement.bindBankCard(_params).then(response => {
          this.applyWithdraw();
        }).catch( (err) => {
          this.$message.error(err);
        })
      },
      /* 修改银行卡账号 */
      updateBankCard () {
        let _params = {
          bank_card_type: this.formWithdrawal.bank_card_type,
          bank_name: this.formWithdrawal.bank_name,
          card_no: this.formWithdrawal.card_no,
          id: this.formWithdrawal.bankId,
          open_account_name: this.formWithdrawal.open_account_name,
          sub_bank_name: this.formWithdrawal.sub_bank_name,
          bank_province_id: this.formWithdrawal.bank_province,
          bank_city_id: this.formWithdrawal.bank_city
        }
        API_settlement.updateBankCard(_params).then(response => {
          // this.$message.success(response.message);
          this.applyWithdraw();
        }).catch( (err) => {
          this.$message.error(err);
        })
      },
      /* 发起提现 */
      applyWithdraw () {
        let bankParams = {
          account_id: this.accountData.accountId,
          amount: this.formWithdrawal.apply_money,
          bank_name: this.formWithdrawal.bank_name,
          card_no: this.formWithdrawal.card_no,
          open_account_name: this.formWithdrawal.open_account_name,
          sub_bank_name: this.formWithdrawal.sub_bank_name,
          withdraw_channel: this.withdrawal_type,
          withdraw_type: 2
        }
        let alyParams = {
          withdraw_channel: this.withdrawal_type,
          withdraw_type: 2,
          amount: this.formWithdrawal.apply_money,
          account_id: this.accountData.accountId,
          other_account_name: this.formWithdrawal.accountName,
          other_account_no: this.formWithdrawal.accountNo,
          other_account_type_name: "支付宝"
        }
        let _params = this.showBank ? bankParams : alyParams;
        API_settlement.applyWithdrawSubmit(_params).then(response => {
          this.loading = false;
          if (response.success){
            this.$message.success('申请提现成功！');
            this.dialogWithdrawal = false;
            this.GET_CountAccount();
            this.$refs['formWithdrawal'].resetFields();
          } else {
            this.$message.error(response.message);
          }
        }).catch( (err) => {
          this.$message.error(err);
          this.loading = false;
        })
      },
      changeType () {
        this.$refs['formWithdrawal'].clearValidate();
      },
      getCityDatas (id, type, clear) {
        let cityId = id;
        let dataType = type;
        $axios.get(this.MixinRegionApi.replace("@id", cityId)).then((response) => {
          if (dataType === 'province') {
            this.bank_provinceDatas = response.data;
          }
          if (dataType === 'city') {
            this.bank_cityDatas = response.data;
          }
          if (clear) {
            this.formWithdrawal.bank_city = null;
          }
        });
      },
      /** 获取短信验证码 */
      getCode() {
        this.loading = true
        this.codeDiasbled = true
        this.timeDown()
        API_settlement.getWithdrawCode().then(response => {
          this.loading = false
          this.$message.success('验证码发送成功，请注意查收！')
        })
      },
      /** 获取短信验证码按钮倒计时 */
      timeDown() {
        timeI = timeI - 1
        this.appendBtnText = `${timeI}秒后重新发送`
        if (timeI === 0) {
          this.appendBtnText = '重新发送'
          this.codeDiasbled = false
          timeFlag = 1
          timeI = 60
          return
        }
        setTimeout(this.timeDown, 1000)
      }
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>
  .mb20 {
    margin-bottom: 20px !important;
  }
  h1 {
    padding-left: 10px;
    margin: 0 0 10px 0;
    border-left: solid 3px #28b779;
    color: #303133;
    font-size: 18px;
    font-weight: normal;
  }
  .count_row {
    padding: 5px 0;
    background: #fff;
    .count_cell {
      padding: 20px;
      .title {
        margin-bottom: 10px;
        font-size: 14px;
      }
      big {
        display: block;
        line-height: 28px;
        font-size: 28px;
      }
      .el-button {
        margin-top: 5px;
      }
    }
  }
  /** 工具条 */
  /deep/ div.toolbar {
    display: none;
  }

  /deep/ .el-table td:not(.is-left) {
    text-align: center;
  }

  .inner-toolbar {
    display: flex;
    width: 100%;
    justify-content: space-between;
    padding: 0 20px;
  }

  .goods-image {
    width: 50px;
    height: 50px;
  }

  /deep/ .dialog-withdrawal {
    .el-dialog__body {
      padding-bottom: 0;
      .el-input {
        &.is-disabled {
          .el-input__inner {
            color: #333;
          }
        }
      }
      .el-input-group__append {
        padding: 0;
        width: 110px;
        color: #fff;
        background-color: #409EFF;
        border-color: #409EFF;
        box-sizing: border-box;
        text-align: center;
        .el-button {
          padding-left: 0;
          padding-right: 0;
        }
      }
      .disabled_append {
        .el-input-group__append {
          background-color: #c8c9cc;
          border-color: #c8c9cc;
          .el-button {
            cursor: not-allowed;
          }
        }
      }
      .row_tips {
        color: #bcbcbc;
        font-size: 12px;
      }
    }
    .el-select.el-select--small{
      width: 100%!important;
    }
  }
  .borderHr{
    width: 100%;
    height: 0;
    border-bottom: 1px dashed #ccc;
    margin-bottom: 15px;
  }
  .showCitySelect{
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-around;
  }
</style>


